import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { NzMessageService } from "ng-zorro-antd";

@Component({
  selector: 'app-upload',
  templateUrl: './upload.component.html',
  styleUrls: ['./upload.component.scss']
})
export class UploadComponent implements OnInit {
  @Input() piclist = [];//图片列表
  @Input() length = 4;//总共长度
  @Input() size = 500;//文件大小 500K
  @Input() uploadname = "上传图片";
  @Input() outWidth = null;
  @Input() outHeight = null;
  @Input() fileList;
  @Output() piclistChange = new EventEmitter();
  @Output() fileListChange = new EventEmitter();
  @Output() deletefun = new EventEmitter();
  @Output() addfun = new EventEmitter();
  @Input() picSizeInfo;
  @Input() readOnly;
  @Input() canChange;
  @ViewChild('upload') upload: ElementRef;//通过@ViewChild获取元素
  uploadclick() {
    this.upload.nativeElement.click();
  }
  constructor(private _message: NzMessageService) {
  }
  delete(index) {
    this.piclist.splice(index, 1);
    this.fileList.splice(index, 1);
    this.fileListChange.emit(this.fileList);
    this.piclistChange.emit(this.piclist);
    this.deletefun.emit();
  }
  addImage(e) {
    var target = e.target;
    let file = target.files[0];
    if (!file) {
      return false;
    }
    var size = file.size;
    var type = file.type;
    let typecheck = new RegExp(/image/i);
    if (!typecheck.test(type)) {
      this._message.create('error', '请上传图片格式');
      return false;
    }
    if (size > 1024 * this.size) {
      this._message.create('error', '最大可上传' + this.size + 'KB的图片');
      return false;
    }
    var reader = new FileReader();
    var img = new Image();

    reader.readAsDataURL(file);

    // img.src = reader.result;
    // img.width = 500;
    // img.height = 400;

    //var uploadlist=this.uploadlist;
    reader.onload = (e) => {
      this.piclist = [];
      this.piclist.push({ src: reader.result });
    }
    this.fileList = [];
    this.fileList.push(file);
    this.fileListChange.emit(this.fileList);
    this.addfun.emit();
  }
  ngOnInit() {

  }
}
